package com.alpha.controller;

import com.alpha.exception.TaskException;
import com.alpha.pojo.dto.SysJobDTO;
import com.alpha.service.SysJobService;
import com.alpha.utils.msg.QueryReqBean;
import com.alpha.utils.msg.QueryRespBean;
import com.alpha.utils.msg.ResponseMsg;
import com.alpha.utils.quartz.CronUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 调度任务信息操作处理
 * @author
 */
@RestController
@RequestMapping("/api/uf/boostor/common/job")
public class SysJobController {

    @Autowired
    private SysJobService jobService;

    /**
     * 查询定时任务列表
     */
    @PostMapping("/searchByPage/v1")
    public ResponseMsg<QueryRespBean<SysJobDTO>> searchByPage(@RequestBody QueryReqBean<SysJobDTO> queryReqBean) {
        return ResponseMsg.OK(jobService.searchByPage(queryReqBean));
    }

    /**
     * 获取定时任务详细信息
     */
    @GetMapping(value = "/findById/{jobId}")
    public ResponseMsg<SysJobDTO> getInfo(@PathVariable("jobId") Long jobId) {
        return ResponseMsg.OK(jobService.selectJobById(jobId));
    }

    /**
     * 新增定时任务
     */
    @PostMapping("/insertSysJob/v1")
    public ResponseMsg<SysJobDTO> add(@RequestBody SysJobDTO sysJobDTO) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(sysJobDTO.getCronExpression())) {
            return ResponseMsg.error("cron表达式不正确");
        }
        return ResponseMsg.OK(jobService.insertJob(sysJobDTO));
    }

    /**
     * 修改定时任务
     */
    @PutMapping("/updateSysJob/v1")
    public ResponseMsg<SysJobDTO> edit(@RequestBody SysJobDTO sysJobDTO) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(sysJobDTO.getCronExpression())) {
            return ResponseMsg.error("cron表达式不正确");
        }
        return ResponseMsg.OK(jobService.updateJob(sysJobDTO));
    }

    /**
     * 定时任务状态修改
     */
    @PutMapping("/changeStatus/v1")
    public ResponseMsg<Integer> changeStatus(@RequestBody SysJobDTO job) throws SchedulerException {
        SysJobDTO newJob = jobService.selectJobById(job.getJobId());
        newJob.setStatus(job.getStatus());
        return ResponseMsg.OK(jobService.changeStatus(newJob));
    }

    /**
     * 定时任务立即执行一次
     */
    @PutMapping("/run/v1")
    public ResponseMsg<String> run(@RequestBody SysJobDTO job) throws SchedulerException {
        jobService.run(job);
        return ResponseMsg.OK();
    }

    /**
     * 删除定时任务
     */
    @DeleteMapping("/remove/{jobIds}")
    public ResponseMsg<Integer> remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException {
        return ResponseMsg.OK(jobService.deleteJobByIds(jobIds));
    }
}
